import React from 'react';
import { Navigate, useLocation } from 'react-router';
import { useAuth } from './authProvider';
import { Spin, Row, Col } from 'antd';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const { isAuthenticated, loading } = useAuth();
  const location = useLocation();

  if (loading) {
    return (
      <Row justify="center" align="middle" style={{ minHeight: '100vh' }}>
        <Col>
          {/* 使用嵌套模式显示提示文字 */}
          <Spin size="large" spinning={true}>
            <div style={{ textAlign: 'center', marginTop: 16 }}>加载中...</div>
          </Spin>
        </Col>
      </Row>
    );
  }

  // 未登录状态，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 已登录，显示子组件
  return <>{children}</>;
};

export default ProtectedRoute;

    